using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace 电商价格监控器
{
    /// <summary>
    /// 通知助手类 - 支持邮件/微信/消息框通知
    /// </summary>
    public static class NotificationHelper
    {
        /// <summary>
        /// 发送通知（根据配置选择通知方式）
        /// </summary>
        public static void SendNotification(string message, ProductMonitor.MonitorConfig config)
        {
            // 消息框通知
            if (config.EnableMessageBoxNotification)
            {
                SendMessageBoxNotification(message);
            }

            // 邮件通知
            if (config.EnableEmailNotification && IsEmailConfigValid(config.Email))
            {
                SendEmailNotification(message, config.Email);
            }

            // 微信通知
            if (config.EnableWeChatNotification && !string.IsNullOrEmpty(config.WeChatWebhookUrl))
            {
                SendWeChatNotification(message, config.WeChatWebhookUrl);
            }
        }

        /// <summary>
        /// 发送消息框通知
        /// </summary>
        public static void SendMessageBoxNotification(string message)
        {
            try
            {
                MessageBox.Show(
                    message,
                    "🔔 价格监控通知",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine($"消息框通知失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        public static void SendEmailNotification(string message, ProductMonitor.EmailConfig config)
        {
            try
            {
                using (SmtpClient client = new SmtpClient(config.SmtpServer, config.SmtpPort))
                {
                    client.EnableSsl = config.EnableSsl;
                    client.Credentials = new NetworkCredential(config.FromEmail, config.FromPassword);

                    MailMessage mail = new MailMessage
                    {
                        From = new MailAddress(config.FromEmail),
                        Subject = "🔔 京东价格监控通知",
                        Body = message,
                        IsBodyHtml = false,
                        BodyEncoding = Encoding.UTF8,
                        SubjectEncoding = Encoding.UTF8
                    };

                    mail.To.Add(config.ToEmail);

                    client.Send(mail);
                    Console.WriteLine("✅ 邮件通知发送成功");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 邮件通知发送失败: {ex.Message}");
                MessageBox.Show(
                    $"邮件发送失败:\n{ex.Message}\n\n请检查邮件配置是否正确。",
                    "邮件通知错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning
                );
            }
        }

        /// <summary>
        /// 发送企业微信机器人通知
        /// </summary>
        public static void SendWeChatNotification(string message, string webhookUrl)
        {
            try
            {
                var data = new
                {
                    msgtype = "text",
                    text = new
                    {
                        content = message
                    }
                };

                string jsonData = JsonConvert.SerializeObject(data);

                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    client.Headers.Add("Content-Type", "application/json");
                    
                    string response = client.UploadString(webhookUrl, jsonData);
                    
                    var result = JsonConvert.DeserializeObject<dynamic>(response);
                    if (result.errcode == 0)
                    {
                        Console.WriteLine("✅ 微信通知发送成功");
                    }
                    else
                    {
                        Console.WriteLine($"❌ 微信通知发送失败: {result.errmsg}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 微信通知发送失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 验证邮件配置是否有效
        /// </summary>
        private static bool IsEmailConfigValid(ProductMonitor.EmailConfig config)
        {
            return !string.IsNullOrEmpty(config.SmtpServer) &&
                   !string.IsNullOrEmpty(config.FromEmail) &&
                   !string.IsNullOrEmpty(config.FromPassword) &&
                   !string.IsNullOrEmpty(config.ToEmail);
        }

        /// <summary>
        /// 发送测试通知
        /// </summary>
        public static void SendTestNotification(ProductMonitor.MonitorConfig config)
        {
            string testMessage = $"📧 这是一条测试通知\n\n" +
                               $"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n" +
                               $"状态: 系统运行正常\n\n" +
                               $"如果您收到此消息，说明通知功能配置正确。";

            SendNotification(testMessage, config);
        }
    }
}


